package com.app.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.app.model.Fw;
import com.app.model.FwAreaStreet;
import com.app.service.IFwAreaStreetService;
import com.app.service.IFwService;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 房屋片区街道 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2025-04-07
 */
@Api(tags = "房屋片区街道")
@RestController
@RequestMapping("/fwAreaStreet")
public class FwAreaStreetController {

    @Autowired
    private IFwAreaStreetService fwAreaStreetService;

    @Autowired
    private IFwService fwService;

    @ApiOperation(value = "获取房屋片区街道数形结构", notes = "获取房屋片区街道数形结构")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fwId", value = "房屋ID", required = true, dataType = "Integer"),
    })
    @GetMapping("/admin/getAreaStreetList")
    public Result getAreaStreetList(String keyword) {
        QueryWrapper<FwAreaStreet> queryWrapper = new QueryWrapper<>();
        if (keyword!= null &&!keyword.equals("")) {
            queryWrapper.like("name", keyword);
        }
        queryWrapper.orderByAsc("id");
        // 获取所有符合条件的记录
        List<FwAreaStreet> allRecords = fwAreaStreetService.list(queryWrapper);
        if (keyword!= null &&!keyword.equals("")){
            return Result.success(allRecords);
        }
        // 按 area_level 分组
        Map<Integer, List<FwAreaStreet>> groupedByLevel = allRecords.stream()
                .collect(Collectors.groupingBy(FwAreaStreet::getAreaLevel));

        List<FwAreaStreet> rootList = groupedByLevel.getOrDefault(0, new ArrayList<>());
        List<FwAreaStreet> childList = groupedByLevel.getOrDefault(1, new ArrayList<>());

        // 构建层级关系
        for (FwAreaStreet root : rootList) {
            List<FwAreaStreet> children = new ArrayList<>();
            for (FwAreaStreet child : childList) {
                if (child.getParentId().equals(root.getId())) {
                    children.add(child);
                }
            }
            root.setChildren(children);
        }

        return Result.success(rootList);
    }


    @ApiOperation(value = "获取房屋片区街道数形结构下拉框", notes = "获取房屋片区街道数形结构下拉框")
    @GetMapping("/admin/getAreaStreetListDropDown")
    public Result getAreaStreetListDropDown(String keyword) {
        QueryWrapper<FwAreaStreet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        if (keyword!= null &&!keyword.equals("")) {
            queryWrapper.like("name", keyword);
        }
        queryWrapper.orderByAsc("id");
        // 获取所有符合条件的记录
        List<FwAreaStreet> allRecords = fwAreaStreetService.list(queryWrapper);
        if (keyword!= null &&!keyword.equals("")){
            return Result.success(allRecords);
        }
        // 按 area_level 分组
        Map<Integer, List<FwAreaStreet>> groupedByLevel = allRecords.stream()
                .collect(Collectors.groupingBy(FwAreaStreet::getAreaLevel));

        List<FwAreaStreet> rootList = groupedByLevel.getOrDefault(0, new ArrayList<>());
        List<FwAreaStreet> childList = groupedByLevel.getOrDefault(1, new ArrayList<>());

        // 构建层级关系
        for (FwAreaStreet root : rootList) {
            List<FwAreaStreet> children = new ArrayList<>();
            for (FwAreaStreet child : childList) {
                if (child.getParentId().equals(root.getId())) {
                    children.add(child);
                }
            }
            root.setChildren(children);
        }

        return Result.success(rootList);
    }




    @ApiOperation(value = "片区街道详情", notes = "片区街道详情")
    @GetMapping("/admin/getFwAreaStreetById")
    public Result getFwAreaStreetById(Integer id) {
        QueryWrapper<FwAreaStreet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        FwAreaStreet fwAreaStreet = fwAreaStreetService.getOne(queryWrapper);
        return Result.success(fwAreaStreet);
    }


    @ApiOperation(value = "删除房屋片区街道", notes = "删除房屋片区街道")
    @GetMapping("/admin/deleteFwAreaStreetById")
    public Result deleteFwAreaStreetById(Integer id) {
        fwAreaStreetService.removeById(id);
        return Result.success("操作成功！");
    }


    @ApiOperation(value = "保存房屋片区街道", notes = "保存房屋片区街道")
    @PostMapping("/admin/saveAreaStreet")
    public Result saveAreaStreet(HttpServletRequest request, @RequestBody FwAreaStreet fwAreaStreet){
        if (fwAreaStreet.getId() == null){
            fwAreaStreet.setCreateTime(LocalDateTime.now());
            fwAreaStreet.setCreateId(StpUtil.getLoginIdAsInt());
            fwAreaStreet.setStatus(1);
            fwAreaStreetService.save(fwAreaStreet);
        }else {
            fwAreaStreet.setUpdateTime(LocalDateTime.now());
            fwAreaStreet.setUpdateId(StpUtil.getLoginIdAsInt());
            fwAreaStreetService.updateById(fwAreaStreet);
        }
        return Result.success("操作成功！");
    }


    @ApiOperation(value = "同步房屋片区街道列表", notes = "同步房屋片区街道列表")
    @GetMapping("/admin/synchronizationAreaStreetList")
    public Result synchronizationAreaStreetList() {

        QueryWrapper<Fw> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("area_name as areaName");
        queryWrapper.groupBy("area_name");
        List<Fw> fwList = fwService.list(queryWrapper);
        for (Fw fw : fwList) {
            if (fw != null && fw.getAreaName()!= null){
                FwAreaStreet fwAreaStreet = new FwAreaStreet();
                fwAreaStreet.setName(fw.getAreaName());
                fwAreaStreet.setAreaLevel(0);
                fwAreaStreet.setCreateTime(LocalDateTime.now());
                fwAreaStreet.setStatus(1);
                fwAreaStreetService.save(fwAreaStreet);

                QueryWrapper<Fw> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.select("street_name");
                queryWrapper1.eq("area_name", fw.getAreaName());
                queryWrapper1.groupBy("street_name");
                List<Fw> fwList1 = fwService.list(queryWrapper1);
                for (Fw fw1 : fwList1) {
                    FwAreaStreet fwAreaStreet1 = new FwAreaStreet();
                    fwAreaStreet1.setName(fw1.getStreetName());
                    fwAreaStreet1.setAreaLevel(1);
                    fwAreaStreet1.setStatus(1);
                    fwAreaStreet1.setParentId(fwAreaStreet.getId());
                    fwAreaStreet1.setCreateTime(LocalDateTime.now());
                    fwAreaStreetService.save(fwAreaStreet1);
                }
            }
        }
        return Result.success("");
    }

    @ApiOperation(value = "保存房屋片区街道列表", notes = "保存房屋片区街道列表")
    @PostMapping("/admin/saveAreaStreetList")
    public Result saveAreaStreetList(HttpServletRequest request,@RequestBody FwAreaStreet fwAreaStreet) {

        String userId = StpUtil.getLoginIdAsString();

        if (fwAreaStreet.getId() == null){
            fwAreaStreet.setCreateTime(LocalDateTime.now());
            fwAreaStreet.setCreateId(Integer.parseInt(userId));
            fwAreaStreet.setStatus(1);
            fwAreaStreetService.save(fwAreaStreet);
        }else {
            fwAreaStreet.setUpdateTime(LocalDateTime.now());
            fwAreaStreet.setUpdateId(Integer.parseInt(userId));
            fwAreaStreetService.updateById(fwAreaStreet);
        }
        return Result.success("操作成功！");
    }


}

